package com.example.skytakeoutserver.util

import com.example.serverbase.ext.Log
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.util.UriComponentsBuilder
import reactor.core.publisher.Mono


object HttpClientUtil {

    private val webClient: WebClient = WebClient.builder().build()
    private val tempMap: Map<String, String> = emptyMap<String, String>()

    /**
     * 发起get
     */
    fun doGet(url: String, params: Map<String, Any>? = null): Mono<String> {
        val uri = UriComponentsBuilder.fromHttpUrl(url).apply {
            params?.forEach { (key, value) ->
                queryParam(key, value)
            }
        }.build().toUri()

        Log.info("GET $uri")
        return webClient.get()
            .uri(uri)
            .retrieve()
            .bodyToMono<String>(String::class.java)
    }

    /**
     * 发起post
     */
    fun doPost(url: String, params: Map<String, Any>? = null): Mono<String> {
        return webClient.post()
            .uri(url)
            .bodyValue(params ?: tempMap)
            .retrieve()
            .bodyToMono(String::class.java)
    }

    /**
     * post 返回 json
     */
    fun doPost4Json(url: String, params: Map<String, Any>? = null): Mono<String> {
        return webClient.post()
            .uri(url)
            .bodyValue(params ?: emptyMap<String, Any>())
            .retrieve()
            .bodyToMono(String::class.java)
    }
}